// pages/order/order.js
import api from '../../../utils/util.js'; // 导入请求类
const app = getApp(),
      ent = app.globalData.ent;
let tempCommodity = []; // 所需商品总和
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navmess:{
      navtitle: "预约",
      backhide: 1,
      topheight: 1
    },
    statusBarHeight: app.globalData.statusBarHeight,
    curIdx: 1,
    ProjectListHeight: 128, // 列表的高度
    top_tabeListIdx: 0,// 顶部的选择ba
    storeId: '', // 门店id
    leftFixedList:[{name:'全部',projectCatId: 0}
    ],
    leftFixedListChooseBeauty: [{name:'服务过',id: 0},{name:'全部',id: ''},], // 选择美容师
    leftFixedListIdx: 0, // 左边固定栏选中的下标
    activeProjectList: [], // 选择项目列表
    activeCommoditySum: 0, // 已选择项目总数
    activeCommodityPricesSum: 0,// 已选择项目价格总价7
    isShowPullList: false, // 默认隐藏
    pullSelect_List_active: '全部', // 下拉列表选择中项
    bottomGuide_bgheight_stauts: false, // false: height=>0%, true: height:=>100%
    staffList: [],// 全部=>美容师列表
    serviceStaffList: [],// 服务过=>美容师列表
    List: [],// 已选中的项目列表
    activeBeautician: '', // 已选中的美容师
    postid: '',// 美容师分类ID
    token: '',// 会员的token
    url: '',// 需要调转的链接和参数
    type: 0, // 0=>正常流程 1=>修改预约
    mineInfo: {}, //门店信息
    Discount:{
      treatmentDiscount: 0, //	疗程折扣
      productDiscount: 0,// 产品折扣
      projectDiscount: 0,// 项目折扣
    }
  },
  // 获取屏幕高都
  getPhoneHeight: function(){
    var query = wx.createSelectorQuery(), self = this;
    query.select('.top-babar').boundingClientRect()
    query.select('.navbar').boundingClientRect()
    query.select('.comonbox').boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec(function(res){
          let scrollHeight = wx.getSystemInfoSync().screenHeight, // 屏幕的高度
              top_babar_height = res[0].height, // 顶部tab元素的高度
              top_Bangs_height = res[1].height, // 顶部自定义导航栏高度
              top_search_height = self.data.top_tabeListIdx==0?0:res[2].height; // 搜索框高度
          let sumheight =  self.data.top_tabeListIdx==0?(scrollHeight - top_babar_height - top_Bangs_height - 60):(scrollHeight - top_babar_height - top_Bangs_height - 60 - top_search_height);
          self.setData({ProjectListHeight: sumheight}); //赋值高度
    })
  },
  // 顶部tab
  getActiveTabeList: function(e){
    let Idx = e.currentTarget.dataset.index,
        storeId = this.data.storeId; 
    this.setData({top_tabeListIdx: Idx});
    this.getPhoneHeight();
    if(Idx == 1){
      // 加载美容师分类
      this.getBeauticianType();
      // 设置左边固定栏被选中
      this.setData({leftFixedListIdx: 1});
      // 加载美容师列表
      this.getBeauticianList({ent: ent, storeId: storeId});
    }
  },
  // 左边固定栏
  getleftFixedList: function(e){
    let dataset = e.currentTarget.dataset,
        typeId = dataset.id, // 分类ID
        top_tabeListIdx = this.data.top_tabeListIdx, // 0选择项目列表 1选择美容师列表
        storeId = this.data.storeId; // 门店列表
      this.setData({leftFixedListIdx: dataset.index})
      if(top_tabeListIdx==0){
        this.getProjectList(typeId); //点击项目分类
      }else{
        let temp = {ent: ent, storeId: storeId, postId: typeId};
        this.getBeauticianList(temp);//点击美容师分类 
      }
  },
  // 获取项目分类
  getTypeList: function(){
      api.post('/mini/appoint/projectCat',{
        ent: '10000'
      }).then(res=>{
        console.log(res)
        let listType = res.result,
            leftFixedList = this.data.leftFixedList;
        for(var i=0;i<listType.length; i++){
          leftFixedList.push(listType[i]);
        }
        this.setData({leftFixedList: this.data.leftFixedList})
      })
  },
  // 获取项目列表 ListNumber 类别类目ID projectCatId
  getProjectList: function(typeId){
    this.setData({activeProjectList: []});
    console.log("企业ID",ent,"门店ID",this.data.storeId,"项目分类ID",typeId,)
    api.post('/mini/appoint/projectList',{
      ent: ent,// 企业编号必传
      storeId: this.data.storeId, // 门店id必传
      projectCatId: typeId,// 分类ID必传
    }).then(res=>{
      let RES_DATA = res.result, activeProjectList = this.data.activeProjectList, 
      projectDiscount = this.data.Discount.projectDiscount,
      List = this.data.List; // 已选择的项目列表
      for(var i=0;i<RES_DATA.length;i++){ // 加载列表
  
        let  tempList = {
          id:  RES_DATA[i].id,
          sign: RES_DATA[i].sign,
          title: RES_DATA[i].name,
          icon: RES_DATA[i].photo,
          number: 0,
          originalPrice: RES_DATA[i].originalPrice,// 原价
          projectDiscount: (RES_DATA[i].originalPrice * parseInt(projectDiscount)) / 100, //会员价
        }
        activeProjectList.push(tempList);
      }

      for(var i=0; i<List.length; i++){ // 显示已选中的项目数量
          for(var j=0;j<activeProjectList.length;j++){
            if(List[i].id == activeProjectList[j].id){ // 发现已选择数量项
              activeProjectList[j].number = List[i].number;
            }
          }
      }
      this.setData({activeProjectList: activeProjectList});
      /**
       * 数据回显列表
       */ 
      if(this.data.type==1 && this.data.mineInfo.settingData!=undefined){
        let mineInfo = this.data.mineInfo.settingData;
        console.log(mineInfo.projects, mineInfo.appointStaffId)
        this.setViewData(mineInfo.projects,mineInfo.appointStaffId, activeProjectList);
      }
    })
  },
  // 数据回显
  setViewData: function(projects, appointStaffId,activeProjectList){
      let ShowListdata = [];
       for(var i in projects){
        for(var j in activeProjectList){
          if(projects[i].projectId == activeProjectList[j].id){
            ShowListdata.push(activeProjectList[j]);
            let settingProject = JSON.parse(JSON.stringify(activeProjectList[j]));
            settingProject.number = projects[i].quantity; // 预约了项目的数量
            app.globalData.list = settingProject;
          }
        }
       }
    // 以下是回显美容师
    let temp = {ent: ent, storeId: this.data.storeId};
    this.getBeauticianList(temp);
  },
  // 获取会员权
  getProjectDiscount: function(token){
    api.post('/mini/my/account/discount',{token: token}).then(res=>{
      /**
       * treatmentDiscount: '', //	疗程折扣
         productDiscount: '',// 产品折扣
         projectDiscount: '',// 项目折扣
       * 
       * **/
      let data = res.result,
      project = data.projectDiscount.replace("%","");
      // product = data.productDiscount.replace("%",""), 
      // project = data.projectDiscount.replace("%","");

      let temp = 'Discount.projectDiscount';
      this.setData({[temp]: project});
      console.log(project);
    })
  },
  // 获取项目详情
  getSigin: function(e){
    let info = e.currentTarget.dataset.info, // 每个被点击的项目的信息
        url = this.data.url, // 要跳转的链接
        List = this.data.List, // 已选中项目列表
        activeBeautician = this.data.activeBeautician, // 已选中的美容师
        activeCommoditySum = this.data.activeCommoditySum,  // 已选中项目总数
        activeCommodityPricesSum =  this.data.activeCommodityPricesSum; // 已选中的项目价格总数
    if(info==undefined){return;}
    let shoppingPayInfo = {
      url: url,
      List: List,
      activeBeautician: activeBeautician,
      activeCommoditySum: activeCommoditySum,
      activeCommodityPricesSum: activeCommodityPricesSum
    }
    var obj = {info: info, shoppingPayInfo: shoppingPayInfo};
    wx.setStorageSync('projectInfo', obj);
    wx.navigateTo({url: '/pages/orders/projectDetails/projectDetails'});
  },
  // 设置选择项目的数量
  settingNumber: function(e){
    let listSettingNumber = e.target.dataset.btn, // 获取加还是减
        getListIndex = e.target.dataset.index, // 获取点击哪个的列表下标
        activeProjectList = this.data.activeProjectList, // 选择列表
        ArrObject = `activeProjectList[${getListIndex}].number`; // 修改数组对象
    if(listSettingNumber == 0){
      this.setData({[ArrObject]: activeProjectList[getListIndex].number-1});
    }else{
      this.setData({[ArrObject]: activeProjectList[getListIndex].number+1});
    }
      this.TotalMerchandise(activeProjectList[getListIndex], getListIndex);
      console.log(activeProjectList[getListIndex]);
  },
  // 处理购买商品总和
  TotalMerchandise: function(list){
    let sign = false; // 是否已经存在
   for(var key in tempCommodity){
    if(tempCommodity[key].id == list.id){ // 存在
      sign = true;
      tempCommodity[key].number = list.number; // 覆盖
    }
   }
   if(sign!=true){tempCommodity.push(list)};
   this.TotalCommodityPrices(tempCommodity);
   for(var key in tempCommodity){
     if(tempCommodity[key].number < 1){
      tempCommodity.splice(key,1);
     }
   }
    console.log(tempCommodity);
    this.setData({List: tempCommodity});
    this.settoUrl();
  },
  // 已选择商品总数和价格
  TotalCommodityPrices: function(list){
    var List = JSON.parse(JSON.stringify(list)), number=0, Price=0,token=this.data.token;
        for(var key in List){
          number += List[key].number; // 商品数量
          Price += (token==''?List[key].originalPrice:List[key].projectDiscount) * List[key].number; // 会员价格
        }
        this.setData({activeCommoditySum: number, activeCommodityPricesSum: Price});
  },
  // 获取选择的美容师
  getSelectBeautician: function(e){
    let sign = e.target.dataset.sign;
    if(sign == this.data.activeBeautician.sign){// 取消预约美容师
      this.setData({activeBeautician: ''});
      wx.showToast({title: '取消美容成功',icon: 'none'});
    }else{
      this.publicToUrl('/pages/orders/technicianDetails/technicianDetails?BeauticianSign=',sign);
    }
  },
  // 获取购物车选中项目/包括清除购物车
  getCarOpction: function(list){
    console.log("lsi",list);
    if(list.detail==0 || Object.getOwnPropertyNames(list).length == 0){ // 清空购物车
      this.setData({List: [], activeCommoditySum: 0,activeCommodityPricesSum: 0});
      for(var key in this.data.activeProjectList){
        let ArrObject = `activeProjectList[${key}].number`; // 修改数组对象
        this.setData({[ArrObject]: 0})
      }
      return;
    }
    let List = list.detail==undefined?list:list.detail.list,
    activeProjectList = this.data.activeProjectList, // 选择列表
    ArrObject = "", Idx = 0;
    for(var key in activeProjectList){
      if(List.id == activeProjectList[key].id){
        console.log("List.id",List.id);
        ArrObject = `activeProjectList[${key}]`; // 修改数组对象
        Idx=key;
      }
    }
    this.setData({[ArrObject]: List});
    this.TotalMerchandise(List, Idx);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    let mineInfo = wx.getStorageSync('mineInfo');
    this.getPhoneHeight();
    this.setData({
      token: this.getLocalCache('token'),
      mineInfo: mineInfo, 
      type: mineInfo.type});
      // this.data.mineInfo.store.id

    let type = mineInfo.type, storeId = mineInfo.store.id;
    this.setData({storeId: "1"});
    if(this.data.token!=""){
      this.getProjectDiscount(this.data.token);// 获取会员折扣
    }

    this.getTypeList(); // 获取项目分类
    this.getProjectList("0"); // 获取项目列表 0=> 所有项目

    app.watch(this.watchProjectList, 'list'); //开始监听项目详情里的购车 <全局属性>!。 this.watchProjectList 回调是方法
    app.watch(this.watchBeautician, 'activeBeautician'); //开始监听选择美容师 <全局属性>!。 this.watchBeautician 回调是方法
    app.watch(this.projectChange, 'projectChange'); //开始监听项目详情 选技师 <全局属性>!。 this.projectChange 回调是方法

  },
  // 监听已返回美容师的信息
  watchBeautician: function(value){
    this.setData({activeBeautician: value, top_tabeListIdx: 0});
    console.log("返回美容师的信息",value);
    this.settoUrl();
  },
  // 监听项目列表数据发生变化
  watchProjectList: function(value){
    console.log("项目列表发生变化", value);
    this.getCarOpction(value, 1); // 判断选择项目列表 是加减还是 清空
  },
  // 监听详情页跳转美容师列表
  projectChange: function(){
    this.toBeauticiaList(); // 开始跳转美容师栏
  },
  // 设置下一步跳转链接和传参
  settoUrl: function(){
    this.setData({url: '/pages/orders/appointmentTime/appointmentTime?'+JSON.stringify({activeBeautician: this.data.activeBeautician, List: this.data.List})});
  },
  // 公共跳转事件
  publicToUrl: function(URL,data){
    let DATA = data==undefined||data==""?null:typeof data== Object||data==Array? JSON.stringify(data):data;
    wx.navigateTo({url: URL + DATA}); //公共跳转
  },
  // 获取token
  getLocalCache: function(parameter){
    return wx.getStorageSync(parameter);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  /**
   * 以下是选择美容师处理模块
  */
  // 获取选中的搜索类别 e.target.dataset.class postid
  getActiveClassName: function(e){
    let name = e.target.dataset.class,
        postid = e.target.dataset.postid;
    this.setData({pullSelect_List_active: name, postid: postid});
    console.log(postid)
    this.set_pullList();
  },
  // 获取美容师分类 /mini/appoint/staffCat
  getBeauticianType: function(){
    this.setData({leftFixedListChooseBeauty:[{name:'服务过',id: 0},{name:'全部',id: ''}]});
    var leftFixedListChooseBeauty = this.data.leftFixedListChooseBeauty;
     api.post('/mini/appoint/staffCat',{
       ent: ent
     }).then((res)=>{
       let RES_DATA = res.result;
       for(var i in RES_DATA){
         let temp = {id: RES_DATA[i].id,name: RES_DATA[i].name};
         leftFixedListChooseBeauty.push(temp);
       }
       this.setData({leftFixedListChooseBeauty: leftFixedListChooseBeauty});
     })
  },
   // 获取美容师列表
  getBeauticianList: function(obj,appointStaffId){
     if(obj === ""|| obj === undefined || obj===null){console.error("缺少参数");return;}
     this.setData({staffList: []});
     api.post('/mini/appoint/staffList',obj).then(res=>{
       let list = res.result,
       staffList = this.data.staffList, 
       serviceStaffList = this.data.serviceStaffList;
       console.log("获取回来的信息",list,obj);
       for(var i in list){
         let temp = {id: list[i].id,
           sign: list[i].sign,// id签名
           name: list[i].name,// 美容师名字
           photo: list[i].photo, // 美容师头像
           postLevelName: list[i].postLevelName, // 美容师职称
           storeId: list[i].storeId,// 门店ID
           storeName: list[i].storeName, // 门店名称
           address: list[i].address, // 门店地址
           count: list[i].count, // 服务次数
         };

         if(this.data.type==1 && this.data.mineInfo.settingData!=undefined){ // 数据回显
            if(temp.id == this.data.mineInfo.settingData.appointStaffId){
              let stemp = JSON.parse(JSON.stringify(temp));
              stemp.indexPhotoUrl = stemp.photo;// 重组一下
              this.setData({activeBeautician: stemp});
              console.log("重组美容师数据",stemp);
            }
         }
         if(list[i].count != 0 && list[i].count!=null){
           serviceStaffList.push(temp); // 服务过的
           this.setData({serviceStaffList: this.data.serviceStaffList});
         }else{
           staffList.push(temp); // 全部，以及筛选过的
           this.setData({staffList: this.data.staffList});
         }
       }
     })
  },
  // 搜索美容师
  searcBeauticianh: function(e){
     let value = e.detail.value, Type = this.data.pullSelect_List_active, Beauty=this.data.leftFixedListChooseBeauty;   //下拉分类
     if(value==""||value==undefined){wx.showToast({
       title: '请输入关键字',icon: 'none',duration: 3000}); return;};
      if(Type == "全部"){// 搜索全部分类的改用户
        this.getBeauticianList({ent: ent, keyword: value}); // 搜索全部分类
        this.setData({leftFixedListIdx: 1});// 选中全部
        return;
      }
      for(var key in Beauty){
        if(Beauty[key].id == this.data.postid){
          this.setData({leftFixedListIdx: key});
        }
      }
      this.getBeauticianList({ent: ent, postId: this.data.postid, keyword: value}); // 按分类搜索
     console.log(this.data.postid)
  },
  // 设置隐藏显示下拉列表
  set_pullList: function(){
    this.setData({isShowPullList: !this.data.isShowPullList})
  },
  getBg_stauts: function(e){
    this.setData({bottomGuide_bgheight_stauts: e.detail})
  },
  // 盒子事件
  hidePullList: function(){
    this.setData({isShowPullList: false})
  },
  // setIdx(检查必要参数)
  setIdx: function(type){
    let Type = type.detail.idx;
    if(Type == 0){
      this.toBeauticiaList(); // 跳转到选择美容师
    }else{
      wx.showToast({title: '至少选择一项项目',icon: 'none',duration: 3000});
    }
  },
  // 跳转确认时间
  toConfirmTime: function(){
    let obj = {
      type: this.data.mineInfo.type, // 0=>正常流程 1=>修改预约
      token: this.data.token,
      store: this.data.mineInfo.store,
      projects: this.data.List,
      appointStaffId: this.data.activeBeautician
    }
    wx.setStorageSync('commAndBea', obj); // 存入确认时间数据
    wx.navigateTo({url: '/pages/orders/appointmentTime/appointmentTime'});
  },
  // 跳转美容师
  toBeauticiaList: function(){
    this.setData({top_tabeListIdx: 1, leftFixedListIdx: 1});
    // 加载美容师分类
    this.getBeauticianType();
    // 加载美容师列表
    this.getBeauticianList({ent: ent, storeId: this.data.storeId}); // 加载美容师列表
     // 屏幕适配
    this.getPhoneHeight();
  }
})